import { EnvironmentService } from 'egret/platform/environment/node/environmentService';
import { ServiceCollection } from 'egret/platform/instantiation/common/serviceCollection';
import { IWindowConfiguration } from 'egret/platform/windows/common/window';
import { IWorkspace, IWorkspaceService } from 'egret/platform/workspace/common/workspace';
import { GameShell } from './gameShell';
import { CreateElectronAPI } from 'game/electronAPI';

export class GameMain {

	/**
	 * 渲染进程启动
	 */
	public startup(configuration: IWindowConfiguration): Promise<void> {

		const mainServices = this.createMainProcessServices();
		const environmentService = new EnvironmentService(configuration, configuration.execPath);

		CreateElectronAPI(configuration.folderPath);

		return this.domContentLoaded().then(() => {
			const shell = new GameShell(
				document.body,
				{
					workspaceService: <IWorkspaceService>{
						_serviceBrand: undefined,
						_workSpace: <IWorkspace>{
							name: "",
							uri: null,
							file: null
						},
						/**
						 * 获取当前workspace
						 */
						getWorkspace(): IWorkspace { return this._workSpace; },
						/**
						 * 获取当前盒式布局的根
						 */
						boxlayout: null,
						/**
						 * 注册盒式布局的根
						 * @param box 
						 */
						registerBoxlayout(box: boxlayout.BoxLayout): void { }
					},
					environmentService
				},
				mainServices,
				configuration,
				null
			);
			shell.open();
		});
	}

	protected createMainProcessServices(): ServiceCollection {
		const serviceCollection = new ServiceCollection();
		//TODO 添加渲染进程更多服务
		return serviceCollection;
	}

	protected domContentLoaded(): Promise<any> {
		return new Promise<any>((c, e) => {
			const readyState = document.readyState;
			if (readyState === 'complete' || (document && document.body !== null)) {
				window.setImmediate(c);
			} else {
				window.addEventListener('DOMContentLoaded', c, false);
			}
		});
	}
}
